﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace SerialPort2Socket
{
    public class EnumHelper
    {
        public static string GetDescription(object value)
        {
            Type type = value.GetType();
            string enumvalue = Enum.GetName(type, value);
            if (!string.IsNullOrEmpty(enumvalue))
            {
                System.Reflection.FieldInfo finfo = type.GetField(enumvalue);
                object[] cAttr = finfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (cAttr.Length > 0)
                {
                    DescriptionAttribute desc = cAttr[0] as DescriptionAttribute;
                    if (desc != null)
                    {
                        enumvalue = desc.Description;
                    }
                }
            }
            return enumvalue;
        }

        public static T ConvertFromString<T>(string value)
        {
            return (T)Enum.Parse(typeof(T), value);
        }
    }
}
